<script setup>
import LayoutFooter from '../Layout/components/LayoutFooter.vue';
import LayoutNav from '../Layout/components/LayoutNav.vue';
import { ref,onMounted } from 'vue';
import { getAddressListAPI, addAddressAPI } from '@/api/user'
import { addOrderAPI } from '@/api/order'
import { addPurchaseAPI } from '@/api/purchase'
import router from '@/router';
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/store/token'

// 获取登录用户信息
const tokenStore = useTokenStore();
// console.log(tokenStore.user);


const checkInfo = ref({})  // 订单对象
const curAddress = ref({})  // 地址对象
const showDialog = ref(false)
const addDialog = ref(false)
const form = ref({
  userId: tokenStore.user.userId,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: ''
})
const isDefault = ref([
  { label: '是', value: 'Y' },
  { label: '否', value: 'N' }
])
const activeAddress = ref({})

//获取订单信息
import { useOrderStore } from '@/store/order';
const orderStore = useOrderStore();
const getCheckInfo = () => {
  checkInfo.value = orderStore.checkInfo
  console.log(checkInfo.value);
    
}
onMounted(() => {
  getCheckInfo();
});
getCheckInfo();

// 获取地址列表
function getAddressList(){
  const id = tokenStore.user.userId
  getAddressListAPI(id).then(res=>{
    if (res.code === 0) {
      console.log(res.data);
      
      activeAddress.value = res.data
      // 查找 isDefault 为 'Y' 的地址
      curAddress.value = activeAddress.value.find(address => address.isDefault == 'Y');
    } else {
      ElMessage.error(res.message || '获取地址失败')
    }
  })
}
getAddressList();

// 切换地址
const switchAddress = (item)=>{
  curAddress.value=item
  showDialog.value=false;
}

// 提交地址
function submitAddress() {
  addAddressAPI(form.value).then(res=>{
    if(res.code === 0){
      ElMessage.success('添加地址成功')
    } else{
      ElMessage.error(res.message || '添加地址失败')
    }
    getAddressList();
  })
}

// 提交订单
function submitOrder(){
  console.log('提交订单');
  // 清空 checkInfo 暂不，支付后清空
  // orderStore.clearCheckInfo();
  let identity = tokenStore.user.identity;
  let data = {
    userId: tokenStore.user.userId,
    storeId: checkInfo.value.salerId,
    goodId: checkInfo.value.goodId,
    skuId: checkInfo.value.selectedSku.skuId,
    amount: checkInfo.value.quantity,
    remark: checkInfo.value.selectedSku.color + ',' + checkInfo.value.selectedSku.size,
    logistics: curAddress.value.province + curAddress.value.city + curAddress.value.district + curAddress.value.detail
  }
  if (identity == '0') {
    addOrderAPI(data).then(res=>{
      if(res.code === 0){
        ElMessage.success('提交订单成功')
        router.push('/orderPay');
      } else{
        ElMessage.error(res.message || '提交订单失败,请重试')
      }
    })
  } else if (identity == '1' || identity == '2'){
    console.log('当前是实体店或批发商用户在采购');
    let data = {
      buyerId: tokenStore.user.userId,
      sellerId: checkInfo.value.salerId,
      goodId: checkInfo.value.goodId,
      skuId: checkInfo.value.selectedSku.skuId,
      amount: checkInfo.value.quantity,
      remark: checkInfo.value.selectedSku.color + ', ' + checkInfo.value.selectedSku.size,
      logistics: curAddress.value.province + curAddress.value.city + curAddress.value.district + curAddress.value.detail
    }
    addPurchaseAPI(data).then(res => {
      if(res.code === 0){
        ElMessage.success('提交订单成功')
        router.push('/orderPay');
      } else{
        ElMessage.error(res.message || '提交订单失败,请重试')
      }
    })
  }
    
}


</script>

<template>
    <LayoutNav></LayoutNav>
    <div class="xtx-pay-checkout-page">
    <div class="container" v-if="checkInfo">
      <div class="wrapper">
        <!-- 收货地址 -->
        <h3 class="box-title">收货地址</h3>
        <div class="box-body">
          <div class="address">
            <div class="text">
              <div class="none" v-if="!curAddress">您需要先添加收货地址才可提交订单。</div>
              <ul v-else>
                <li><span>收<i />货<i />人：</span>{{ curAddress.name }}</li>
                <li><span>联系方式：</span>{{ curAddress.phone }}</li>
                <li><span>收货地址：</span>{{ curAddress.province }}{{ curAddress.city }}{{ curAddress.district }}{{ curAddress.detail }}</li>
              </ul>
            </div>
            <div class="action">
              <el-button size="large" @click="showDialog=true">切换地址</el-button>
              <el-button size="large" @click="addDialog = true">添加地址</el-button>
            </div>
          </div>
        </div>
        <!-- 商品信息 -->
        <h3 class="box-title">商品信息</h3>
        <div class="box-body">
          <table class="goods">
            <thead>
              <tr>
                <th width="520">商品信息</th>
                <th width="170">单价</th>
                <th width="170">数量</th>
                <th width="170">实付</th>
              </tr>
            </thead>
            <tbody>
              <!-- <tr v-for="i in checkInfo.value" :key="i.good_id">
                <td>
                  <a href="javascript:;" class="info">
                    <img :src="i.picture" alt="">
                    <div class="right">
                      <p>{{ i.name }}</p>
                      <p>{{ i.sku }}</p>
                      <p>{{ i.salerName }}</p>
                    </div>
                  </a>
                </td>
                <td>&yen;{{ i.price }}</td>
                <td>{{ i.num }}</td>
                <td>&yen;{{ i.totalPrice }}</td>
              </tr> -->
              <tr >
                <td>
                  <a href="javascript:;" class="info">
                    <img :src="checkInfo.selectedSku.image" alt="">
                    <div class="right">
                      <p>{{ checkInfo.name }}</p>
                      <p><span>颜色：{{ checkInfo.selectedSku.color }}</span> <span>尺寸：{{ checkInfo.selectedSku.size }}</span></p>
                      <p>{{ checkInfo.salerName }}</p>
                    </div>
                  </a>
                </td>
                <td>&yen;{{ checkInfo.price }}</td>
                <td>{{ checkInfo.quantity }}</td>
                <td>&yen;{{ checkInfo.totalPrice }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 金额明细 -->
        <h3 class="box-title">金额明细</h3>
        <div class="box-body">
          <div class="total">
            <!-- <dl>
              <dt>商品件数：</dt>
              <dd style="font-size: large;">{{ totalNum }} 件</dd>
            </dl>
            <dl>
              <dt>应付总额：</dt>
              <dd style="font-size: large;">¥{{ totalPrice }}</dd>
            </dl> -->
            <dl>
              <dt>商品件数：</dt>
              <dd style="font-size: large;">{{ checkInfo.quantity }} 件</dd>
            </dl>
            <dl>
              <dt>应付总额：</dt>
              <dd style="font-size: large;">¥{{ checkInfo.totalPrice }}</dd>
            </dl>
          </div>
        </div>
        <!-- 提交订单 -->
        <div class="submit">
          <el-button @click='submitOrder' type="primary" size="large" >提交订单</el-button>
        </div>
      </div>
    </div>
  </div>
  <!-- 切换地址 -->
  <el-dialog v-model="showDialog" title="切换收货地址" width="30%" center>
    <div class="addressWrapper">
        <!-- v-if="activeAddress.value!=null" :class="{active:activeAddress.id===item.id}" -->
        <div class="text item"  v-for="item in activeAddress" 
         :key="item.addressid"
         @click="switchAddress(item)">
            <ul>
                <li><span>收<i />货<i />人：</span>{{ item.name }} </li>
                <li><span>联系方式：</span>{{ item.phone }}</li>
                <li><span>收货地址：</span>{{ item.province }} {{ item.city }} {{ item.district }} {{ item.detail }}</li>
            </ul>
        </div>
    </div>
    </el-dialog>
    <!-- 添加地址 -->
    <el-dialog v-model="addDialog " title="添加地址" width="30%">
      <el-form :model="form" label-width="80px">
          <el-form-item label="收货人">
          <el-input v-model="form.name" placeholder="请输入收货人姓名"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
          <el-input v-model="form.phone" placeholder="请输入收货人联系电话"/>
          </el-form-item>
          <el-form-item label="收货地址">
            <el-input v-model="form.province" placeholder="请输入省份"/>
            <el-input style="margin-top: 3px;" v-model="form.city" placeholder="请输入市"/>
            <el-input style="margin-top: 3px;" v-model="form.district" placeholder="请输入区县"/>
            <el-input style="margin-top: 3px;" v-model="form.detail" placeholder="请输入详细地址"/>
          </el-form-item>
          <el-form-item label="默认地址">
            <el-cascader
              v-model="form.isDefault[0]"
              :options="isDefault"
              placeholder="是否设为默认地址"
              clearable
              style="width: 100%"
            />
          </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitAddress">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <LayoutFooter></LayoutFooter>
</template>

<style lang="scss" scoped>
.xtx-pay-checkout-page {
  margin: 15px;

  .wrapper {
    background: #fff;
    padding: 0 20px;
    border-radius: 15px;

    .box-title {
      font-size: 16px;
      font-weight: normal;
      padding-left: 10px;
      line-height: 70px;
      border-bottom: 1px solid #f5f5f5;
    }

    .box-body {
      padding: 0px 0;
    }
  }
}

.address {
  border: 1px solid #f5f5f5;
  display: flex;
  align-items: center;

  .text {
    flex: 1;
    min-height: 90px;
    display: flex;
    align-items: center;

    .none {
      line-height: 90px;
      color: #999;
      text-align: center;
      width: 100%;
    }

    >ul {
      flex: 1;
      padding: 20px;

      li {
        line-height: 30px;

        span {
          color: #999;
          margin-right: 5px;

          >i {
            width: 0.5em;
            display: inline-block;
          }
        }
      }
    }

    >a {
      color: $xtxColor;
      width: 160px;
      text-align: center;
      height: 90px;
      line-height: 90px;
      border-right: 1px solid #f5f5f5;
    }
  }

  .action {
    width: 420px;
    text-align: center;

    .btn {
      width: 140px;
      height: 46px;
      line-height: 44px;
      font-size: 14px;

      &:first-child {
        margin-right: 10px;
      }
    }
  }
}

.goods {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;

  .info {
    display: flex;
    text-align: left;
    align-items: center;
    padding-left: 20%;

    img {
      width: 70px;
      height: 70px;
      margin-right: 20px;
    }

    .right {
      line-height: 24px;

      p {
        &:last-child {
          color: #999;
        }
      }
    }
  }

  tr {
    th {
      background: #f5f5f5;
      font-weight: normal;
    }

    td,
    th {
      text-align: center;
      padding: 20px;
      border-bottom: 1px solid #f5f5f5;

      &:first-child {
        border-left: 1px solid #f5f5f5;
      }

      &:last-child {
        border-right: 1px solid #f5f5f5;
      }
    }
  }
}

.my-btn {
  width: 228px;
  height: 50px;
  border: 1px solid #e4e4e4;
  text-align: center;
  line-height: 48px;
  margin-right: 25px;
  color: #666666;
  display: inline-block;

  &.active,
  &:hover {
    border-color: $xtxColor;
  }
}

.total {
  dl {
    display: flex;
    justify-content: flex-end;
    line-height: 50px;

    dt {
      i {
        display: inline-block;
        width: 2em;
      }
    }

    dd {
      width: 240px;
      text-align: right;
      padding-right: 70px;

      &.price {
        font-size: 20px;
        color: $priceColor;
      }
    }
  }
}

.submit {
  text-align: right;
  padding: 60px;
  border-top: 1px solid #f5f5f5;
}

.addressWrapper {
  max-height: 500px;
  overflow-y: auto;
}

.text {
  flex: 1;
  min-height: 90px;
  display: flex;
  align-items: center;

  &.item {
    border: 1px solid #f5f5f5;
    margin-bottom: 10px;
    cursor: pointer;

    &.active,
    &:hover {
      border-color: $xtxColor;
      background: lighten($xtxColor, 50%);
    }

    >ul {
      padding: 10px;
      font-size: 14px;
      line-height: 30px;
    }
  }
}

</style>